package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;
import dao.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override//
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BlogDao blogDao = new BlogDao();
        String blogId = req.getParameter("blogId");

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (blogId == null) {
            //输入作者的序号,输出作者的博文
            List<Blog> blogs = blogDao.getBlogs(user.getUserId());
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        } else {
            //输出作者的详细博文
            int a=(int) blogId.charAt(1)-48;
            Blog blog = blogDao.getBlog(a, user.getUserId());
            if (blog == null) {
                blog = new Blog();
            }
            String respJson = objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session= req.getSession();
        if(session==null){
            resp.setContentType("text/html;chaeset=utf8");
            resp.getWriter().write("用户未登陆！无法发布博客");
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录! 无法发布博客!");
            return;
        }
        req.setCharacterEncoding("utf8");
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        if(title==null||content==null||"".equals(title)||"".equals(content)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("标题或者正文为空");
            return;
        }
        //获取博客数目。
        BlogDao blogDao=new BlogDao();
        int num=blogDao.getBlognum(user.getUserId());
        Blog blog=new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        //blog.setBlogId(num);
        blogDao.insert(blog);
        resp.sendRedirect("./html/list.html");
    }
}



